<link rel="stylesheet" href="assets/store/css/goods.css?v=<?= $version ?>">
<link rel="stylesheet" href="assets/common/plugins/umeditor/themes/default/css/umeditor.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<div class="row-content am-cf">
<div id="app">
    <div class="container mt-5">
        <h2 class="text-center mb-4" style="font-size: 1.8em;">医生排班</h2>

        <!-- 默认当前月份 -->
        <div class="form-group row">
            <label for="month" class="col-sm-2 col-form-label" style="font-size: 1.5em;">月份:</label>
            <!-- 修改样式 -->
            <div class="col-sm-10">
                <input type="month" v-model="selectedMonth" class="date-clickable" @change="generateDays" style="font-size: 1.5em;">
            </div>
        </div>
    
        <!-- 排班表格 -->
        <table class="table table-bordered mt-4" v-if="weeks.length > 0">
            <!-- 周标题行 -->
            <thead>
                <tr>
                    <th v-for="day in daysOfWeek" :key="day" style="font-size: 1.3em; text-align: center;">{{ day }}</th>
                </tr>
            </thead>
            <!-- 日期显示和选择行 -->
            <tbody>
                <tr v-for="(week, index) in weeks" :key="index">
                    <!-- <td v-for="day in week" :key="day.date" class="text-center" style="padding: 1em;">
                        <div v-if="day.date" class="date-box">
                            <div class="date-number">{{ day.date ? day.date : '' }}</div>
                            <div class="checkboxes">
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="schedule[day.date].morning"> 上午
                                </label>
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="schedule[day.date].afternoon"> 下午
                                </label>
                            </div>
                        </div>
                    </td> -->
                    <td v-for="day in week" :key="day.date" class="text-center" style="padding: 1em;">
                    <div v-if="day.date" class="date-box">
                        <div class="date-number">{{ day.date }}</div>
                        <div class="checkboxes">
                            <div class="morning">
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="schedule[day.date].morning"> 上午
                                </label>
                                <input type="number" v-model="schedule[day.date].morning_num" min="0" placeholder="上午数量" style="width: 60px;">
                            </div>
                            <div class="morning">
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="schedule[day.date].afternoon"> 下午
                                </label>
                                <input type="number" v-model="schedule[day.date].afternoon_num" min="0" placeholder="下午数量" style="width: 60px;">
                            </div>
                        </div>
                    </div>
                    </td>
                </tr>
            </tbody>
        </table>

        <button class="btn btn-primary btn-lg mt-4" @click="submitSchedule">提交排班</button>
    </div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="assets/common/js/ddsort.js"></script>
<script src="assets/common/plugins/umeditor/umeditor.config.js?v=<?= $version ?>"></script>
<script src="assets/common/plugins/umeditor/umeditor.min.js"></script>
<script src="assets/store/js/goods.spec.js?v=<?= $version ?>"></script>

<!-- <script>
new Vue({
    el: '#app',
    data() {
        const today = new Date();
        const currentMonth = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
        return {
            selectedMonth: currentMonth,
            days: [],
            weeks: [],
            daysOfWeek: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
            schedule: {}
        };
    },
    mounted() {
        this.generateDays();
    },
    methods: {
        generateDays() {
            if (!this.selectedMonth) return;
            const [year, month] = this.selectedMonth.split('-');
            const daysInMonth = new Date(year, month, 0).getDate();
            const allDays = Array.from({ length: daysInMonth }, (_, i) => {
                const day = `${this.selectedMonth}-${String(i + 1).padStart(2, '0')}`;
                const date = new Date(day);
                const weekday = date.getDay();
                return { date: day, weekday };
            });

            // 按周分组，并保证每周从周日到周六排列
            this.weeks = [];
            let week = Array(7).fill({ date: null });
            allDays.forEach(day => {
                if (day.weekday === 0 && week.some(d => d.date)) {
                    this.weeks.push(week);
                    week = Array(7).fill({ date: null });
                }
                week[day.weekday] = day;
            });
            if (week.some(d => d.date)) this.weeks.push(week);

            // 初始化排班信息
            allDays.forEach(day => {
                if (!this.schedule[day.date]) {
                    this.$set(this.schedule, day.date, { morning: false, afternoon: false });
                }
            });
        },
        submitSchedule() {
            const selectedSchedule = [];
            for (const date in this.schedule) {
                const times = this.schedule[date];
                const selectedTimes = Object.keys(times).filter(time => times[time]);
                
                if (selectedTimes.length > 0) {
                    const entry = {
                        goods_id: this.selectedDoctor, // 医生ID
                        day: date, // 日期
                        morning: selectedTimes.includes("morning") ? 1 : 0,
                        afternoon: selectedTimes.includes("afternoon") ? 1 : 0
                    };
                    selectedSchedule.push(entry);
                }
            }

            fetch('/store/goods/editpaiban/goods_id/<?= $goods_id ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ schedule: selectedSchedule })
            })
            .then(response => response.json())
            .then(data => {
                layer.msg('排班成功', {
                    time: 1500 // 提示1.5秒后跳转
                }, () => {
                    window.location.href = '/index.php?s=/store/goods/index'; // 跳转到目标页面
                });
            })
            .catch(error => {
                console.error('提交失败:', error);
            });
        }
        
    }
});
</script> -->
<script>
new Vue({
    el: '#app',
    data() {
        const today = new Date();
        const currentMonth = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
        return {
            selectedMonth: currentMonth,
            days: [],
            weeks: [],
            daysOfWeek: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
            schedule: {}
        };
    },
    mounted() {
        this.generateDays();
        this.loadPaibanData();
    },
    methods: {
        loadPaibanData() {
            axios.get(`/store/goods/getPaibanData?goods_id=<?= $goods_id ?>&month=${this.selectedMonth}`)
                .then(response => {
                    const paibanData = response.data.paiban;
                    paibanData.forEach(item => {
                        const day = item.day;
                        this.$set(this.schedule, day, {
                            morning: item.morning === 1,
                            afternoon: item.afternoon === 1,
                            morning_num: item.morning_num || 0,
                            afternoon_num: item.afternoon_num || 0
                        });
                    });
                })
                .catch(error => {
                    console.error('加载排班数据失败:', error);
                });
        },
        generateDays() {
            if (!this.selectedMonth) return;

            const [year, month] = this.selectedMonth.split('-');
            const daysInMonth = new Date(year, month, 0).getDate();
            const allDays = Array.from({ length: daysInMonth }, (_, i) => {
                const day = `${this.selectedMonth}-${String(i + 1).padStart(2, '0')}`;
                const date = new Date(day);
                const weekday = date.getDay();
                return { date: day, weekday };
            });

            this.weeks = [];
            let week = Array(7).fill({ date: null });
            allDays.forEach(day => {
                if (day.weekday === 0 && week.some(d => d.date)) {
                    this.weeks.push(week);
                    week = Array(7).fill({ date: null });
                }
                week[day.weekday] = day;
            });
            if (week.some(d => d.date)) this.weeks.push(week);

            allDays.forEach(day => {
                if (!this.schedule[day.date]) {
                    this.$set(this.schedule, day.date, { 
                        morning: false, 
                        afternoon: false,
                        morning_num: 0,
                        afternoon_num: 0 
                    });
                }
            });

            this.loadPaibanData();
        },
        submitSchedule() {
            const selectedSchedule = [];
            for (const date in this.schedule) {
                const times = this.schedule[date];
                const selectedTimes = Object.keys(times).filter(time => times[time]);

                if (selectedTimes.length > 0) {
                    const entry = {
                        goods_id: this.selectedDoctor,
                        day: date,
                        morning: times.morning ? 1 : 0,
                        afternoon: times.afternoon ? 1 : 0,
                        morning_num: times.morning_num || 0,
                        afternoon_num: times.afternoon_num || 0
                    };
                    selectedSchedule.push(entry);
                }
            }

            fetch('/store/goods/editpaiban/goods_id/<?= $goods_id ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ schedule: selectedSchedule })
            })
            .then(response => response.json())
            .then(data => {
                layer.msg('排班成功', {
                    time: 1500 
                }, () => {
                    window.location.href = '/index.php?s=/store/goods/index';
                });
            })
            .catch(error => {
                console.error('提交失败:', error);
            });
        }
    }
});
</script>
<style>
.date-box {
    width: 100px;
    height: 100px;
    /* border: 1px solid #ccc; */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
}

.date-number {
    font-size: 1.1em;
    margin-bottom: 5px;
}

.checkboxes {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    width: 100%;
}

.morning{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}

.checkbox-label {
    font-size: 0.9em;
    display: flex;
    align-items: center;
}
input[type="number"] {
    width: 60px;
    margin-left: 5px;
    font-size: 0.9em;
    text-align: center;
}
</style>